package com.goldmantis.alitrip.common.httpclient;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author:Shmily
 * @Description: ApiService是单例  但是即使在Spring配置文件中设置了CloseableHttpClient多例，
 * 但是由于单例注入的原则，此处CloseableHttpClient只会注入一次。
 * 通用问题：如何在单例对象中注入多例对象？
 * 实现 BeanFactoryAware 接口 由容器帮我们处理
 * @Date:Create in 11:35 2017/11/18
 */
@Service
public class ApiService implements BeanFactoryAware {

    //此对象不能由Spring注入，而应该由容器来获取，因为容器中指定这是一个多例
//    @Autowired
//    private CloseableHttpClient client;

    @Autowired(required = false)
    private RequestConfig requestConfig;

    private BeanFactory beanFactory;

    private CloseableHttpClient getHttpClient(){
        return beanFactory.getBean(CloseableHttpClient.class);
    }

    /**
     * 封装get请求
     * @param url
     * @return
     * @throws IOException
     */
    public String doGet(String url) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        CloseableHttpResponse response = null;

        try {
            response = getHttpClient().execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return null;
    }

    public String doGet(String url, Map<String, String> params) throws IOException, URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder(url);

        for (Map.Entry<String, String> entry : params.entrySet()) {
            uriBuilder.setParameter(entry.getKey(), entry.getValue());
        }
        return this.doGet(uriBuilder.build().toString());
    }

    public HttpResult doPost(String url, Map<String, String> params) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(this.requestConfig);
        if (null != params) {
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(parameters);
            httpPost.setEntity(urlEncodedFormEntity);
        }

        CloseableHttpResponse response = null;
        try {
            response = getHttpClient().execute(httpPost);
            return new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } finally {
            if (null != response) {
                response.close();
            }
        }
    }

    public HttpResult doPostJson(String url, String json) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(this.requestConfig);
        if (StringUtils.isNotEmpty(json)) {
            StringEntity stringEntity=new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(stringEntity);
        }

        CloseableHttpResponse response = null;
        try {
            response = getHttpClient().execute(httpPost);
            return new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } finally {
            if (null != response) {
                response.close();
            }
        }
    }

    public HttpResult doPost(String url) throws IOException {
        return this.doPost(url, null);
    }

    /**
     * 该方法是在Spring容器初始化时调用此方法，传入BeanFactory
     * @param beanFactory bean 工厂
     * @throws BeansException
     */
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory=beanFactory;
    }
}
